package models

import (
	"context"
	"errors"
	"go-chain-api/global"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type GenerateAddressConfig struct {
	Id          string `bson:"_id,omitempty" json:"id"`
	ChainId     uint   `bson:"chainId" json:"chainId"`
	ChainName   string `bson:"chainName" json:"chainName"`
	Address     string `bson:"address" json:"address"`
	Token       string `bson:"token" json:"token"`
	CallBackUrl string `bson:"callBackUrl" json:"callBackUrl"`
	UserId      string `bson:"userId" json:"userId"`
	PrivateKey  string `bson:"privateKey" json:"privateKey"`
	Type        string `bson:"type" json:"type"`
}

// Insert 插入
func (g GenerateAddressConfig) Insert() error {
	client := global.DBEngine.Database(global.DbConfig.DbName).Collection("generate_address_config")
	_, err := client.InsertOne(context.TODO(), g)
	if err != nil {
		return err
	}
	return nil
}

// DeleteById 删除
func (g GenerateAddressConfig) DeleteById(id string) error {
	client := global.DBEngine.Database(global.DbConfig.DbName).Collection("generate_address_config")
	objID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return err
	}
	deleteResult, err := client.DeleteOne(context.TODO(), bson.M{"_id": objID})
	if err != nil {
		return err
	}
	if deleteResult.DeletedCount == 0 {
		return errors.New("检查ID是否正确")
	}
	return nil
}
